package com.firebird.kotlin.mall.goods.module.goods.detail

//import com.firebird.kotlin.mall.library.ext.onClick

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import cn.bingoogolapple.bgabanner.BGABanner
import com.bumptech.glide.Glide
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import com.firebird.kotlin.mall.goods.R
import com.firebird.kotlin.mall.goods.core.GoodsConstant
import com.firebird.kotlin.mall.goods.data.AddCartReq
import com.firebird.kotlin.mall.goods.data.GoodDetails
import com.firebird.kotlin.mall.goods.di.module.GoodsModule
import com.firebird.kotlin.mall.goods.event.AddCartEvent
import com.firebird.kotlin.mall.goods.event.GoodsDetailhtmlEvent
import com.firebird.kotlin.mall.goods.event.SkuChangedEvent
import com.firebird.kotlin.mall.goods.event.UpdateCartSizeEvent
import com.firebird.kotlin.mall.goods.injection.component.DaggerGoodsFragmentComponent
import com.firebird.kotlin.mall.goods.widget.GoodsSkuPopView
import com.firebird.kotlin.mall.library.ext.onClick
import com.firebird.kotlin.mall.library.mvp.view.activity.BaseActivity
import com.firebird.kotlin.mall.library.mvp.view.fragment.BaseMvpFragment
import com.firebird.kotlin.mall.library.util.Date2Utils.getNow
import com.firebird.kotlin.mall.library.util.LogUtils
import okhttp3.RequestBody
import okhttp3.ResponseBody

/*
  商品详情Tab One
 */
class GoodsDetailTabOneFragment : BaseMvpFragment<GoodsDetailPresenter>(), GoodsDetailContract.View,BGABanner.Adapter<ImageView, String>, BGABanner.Delegate<ImageView, String> {
    private lateinit var mSkuPop: GoodsSkuPopView
    //SKU弹层出场动画
    private lateinit var mAnimationStart: Animation
    //SKU弹层退场动画
    private lateinit var mAnimationEnd: Animation

    private var mCurGoods: GoodDetails? = null
    private var mBgaBanner: BGABanner? = null
    private var mSkuView:RelativeLayout?=null
    private var mGoodsDescTv:TextView?=null
    private var mGoodsPriceTv:TextView?=null
    private var mSkuSelectedTv:TextView?=null
    private var mSkuLabelTv:TextView?=null
    //配置numBanner数据源
    //  通过传入数据模型并结合 Adapter 的方式配置数据源。这种方式主要用于加载网络图片
    override fun fillBannerItem(banner: BGABanner?, itemView: ImageView, model: String?, position: Int) {
        LogUtils.d("fillbanneritem:"+itemView.toString())
        LogUtils.d("position:"+position.toString()+" url:"+model.toString())
        Glide.with(this)
                .load(model)
               // .load("http://res.lgdsunday.club/poster-1.png")
               // .apply(RequestOptions()
                .placeholder(R.drawable.main_bagbanner_holder).error(R.drawable.main_bagbanner_holder)
                .dontAnimate()
                .centerCrop()
                .into(itemView)
    }

    override fun onBannerItemClick(banner: BGABanner?, itemView: ImageView?, model: String?, position: Int) {
        //Toast.makeText()
        //makeText(this, "点击了第" + (position + 1) + "页", Toast.LENGTH_SHORT).show()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        mPresenter.onAttach(this)
        return inflater.inflate(R.layout.fragment_goods_detail_tab_one, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBgaBanner=view.findViewById<BGABanner>(R.id.mGoodsDetailBanner)
        mSkuView=view.findViewById<RelativeLayout>(R.id.mSkuView)
        mGoodsDescTv=view.findViewById<TextView>(R.id.mGoodsDescTv)
        mGoodsPriceTv=view.findViewById<TextView>(R.id.mGoodsPriceTv)
        mSkuSelectedTv=view.findViewById<TextView>(R.id.mSkuSelectedTv)
        mSkuLabelTv=view.findViewById<TextView>(R.id.mSkuLabelTv)
        initView()
        initAnim()
        initSkuPop()
        loadData()
        initObserve()
    }

    override fun performInject() {
        DaggerGoodsFragmentComponent.builder().fragmentComponent(mFragmentComponent)
                .goodsModule(GoodsModule()).build().inject(this)
    }

    /*
      初始化视图
     */
    private fun initView() {

        //配置适配器和点击监听事件
        mBgaBanner?.setAdapter(this)
        mBgaBanner?.setDelegate(this)

        //sku弹层

        mSkuView?.onClick {
            mSkuPop.showAtLocation((activity as GoodsDetailActivity).contentView
                    , Gravity.BOTTOM and Gravity.CENTER_HORIZONTAL,
                    0, 0
            )
            (activity as BaseActivity).contentView.startAnimation(mAnimationStart)
        }
    }

    /*
      初始化缩放动画
   */
    private fun initAnim() {
        mAnimationStart = ScaleAnimation(
                1f, 0.95f, 1f, 0.95f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        mAnimationStart.duration = 500
        mAnimationStart.fillAfter = true


        mAnimationEnd = ScaleAnimation(
                0.95f, 1f, 0.95f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        mAnimationEnd.duration = 500
        mAnimationEnd.fillAfter = true
    }

    /*
      初始化sku弹层
     */
    private fun initSkuPop() {
        mSkuPop = GoodsSkuPopView(activity!!)
        mSkuPop.setOnDismissListener{
            (activity as BaseActivity).contentView.startAnimation(mAnimationEnd)
        }
    }

    /*
      加载数据
     */
    private fun loadData() {
        mPresenter.getGoodsDetailList(activity!!.intent.getIntExtra(GoodsConstant.KEY_GOODS_ID, -1))
    }

    override fun onGetGoodsDetailError(message: String?) {
        LogUtils.d("onGetGoodsDetailError:")
        LogUtils.d(message.toString())
    }
    /*
       获取商品详情 回调
     */
    override fun onGetGoodsDetailResult(result: GoodDetails) {

         mCurGoods = result

        val mTips:List<String> = listOf()
        val mMutableList=mTips.toMutableList()
        LogUtils.d("onGetGoodsDetailResult:")
        LogUtils.d(result.errno.toString()+":"+result.errmsg)
        for((index,value) in mCurGoods!!.data.info.gallery.withIndex())
        {
            mMutableList.add(index.toString())
        }
        mBgaBanner?.setData(mCurGoods!!.data.info.gallery, mMutableList)

       // http://106.12.11.1:8080/wx/goods/detail?id=1064006
        mGoodsDescTv?.setText( "${mCurGoods!!.data.info.name} 描述：${mCurGoods!!.data.info.brief}")

        mGoodsPriceTv?.setText( "到手价￥${mCurGoods!!.data.info.retailPrice} 原价￥${mCurGoods!!.data.info.counterPrice}")
        mSkuSelectedTv?.setText( mCurGoods!!.data.info.name)

        mSkuLabelTv?.setText(mCurGoods!!.data.info.goodsSn)

        Bus.send(GoodsDetailhtmlEvent(mCurGoods!!.data.info.detail))

        loadPopData(result)

    }

    /*
      加载SKU数据
     */
    private fun loadPopData(result: GoodDetails) {
        mSkuPop.setGoodsIcon(result.data.info.picUrl)
        mSkuPop.setGoodsCode(result.data.info.goodsSn)
        mSkuPop.setGoodsPrice(result.data.info.counterPrice.toLong())

       // mSkuPop.setSkuData(result.data.attribute)

    }

    /*
      监听SKU变化及加入购物车事件
     */
    private fun initObserve(){
        Bus.observe<SkuChangedEvent>()
                .subscribe {
                    mSkuSelectedTv?.text = mSkuPop.getSelectSku() +GoodsConstant.SKU_SEPARATOR + mSkuPop.getSelectCount()+"件"
                }.registerInBus(this)

        Bus.observe<AddCartEvent>()
                .subscribe {
                    addCart()
                }.registerInBus(this)
    }

    /*
      取消事件监听
     */
    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    /*
      加入购物车
     */
    private fun addCart(){
        //val id=mCurGoods!!.info.id
        val userId=1
        val goodsId=mCurGoods!!.data.info.id
        val goodsSn=mCurGoods!!.data.info.goodsSn.toString()
        val goodsName=mCurGoods!!.data.info.name
        val productId=mCurGoods!!.data.info.id.toLong()
        var price=mCurGoods!!.data.info.retailPrice
        val number=mSkuPop.getSelectCount()//mSkuPop.getSelectSku()
        val specifications=mCurGoods!!.data.info.name
        val checked=false
        val picUrl=mCurGoods!!.data.info.picUrl
        val addTime=getNow()
        val updateTime= getNow()
        val deleted=mCurGoods!!.data.info.deleted
        val addCart= AddCartReq(userId,goodsId,goodsSn,goodsName,productId,price,number,
                 checked,picUrl)//,addTime,updateTime,deleted) //specifications
        LogUtils.d("addcart:" )
        LogUtils.d(addCart.toString())
        // 构建请求参数
        //val map: MutableMap<String, ?> = HashMap()
        var  map:HashMap<String, RequestBody> = HashMap<String, RequestBody>()
       // map.put("version",ApiClient.createRequestBody(AppConstants.API_VERSION))
        //val userid=1
        // map.put("userId",userid)// param_1：参数名；param1：参数值
        //map["cart"] = RequestBody.create(MediaType.parse("text/plain"), addCart)

        mCurGoods?.let {
           mPresenter.addCart(
                    4,addCart
                    )
        }

    }

    /*
      加入购物车 回调
     */
    override fun onAddCartResult(result: Int) = Bus.send(UpdateCartSizeEvent())
}
